/*
** get_next_line.c for get_next_line in /home/chassa_m/rendu/CPE_2013_getnextline
** 
** Made by chassa_m
** Login   <chassa_m@epitech.net>
** 
** Started on  Sun Nov 24 21:29:23 2013 chassa_m
** Last update Tue Nov 26 13:06:15 2013 chassa_m
*/

#include	<stdlib.h>
#include	"get_next_line.h"

static void	*my_malloc(unsigned int size)
{
  void		*p;

  if ((p = malloc(size)) == 0)
    return (NULL);
  return (p);
}

static int	my_strlen(char *str)
{
  int		i;

  i = 0;
  while (str[i])
    i = i + 1;
  return (i);
}

static char	*my_strncpy(char *dest, char *src, int nb)
{
  int		i;

  i = 0;
  while (src[i] != '\0' && nb > 0) /**/
    {
      dest[i] = src[i];
      nb = nb - 1;
      i = i + 1;
    }
  /*if (i == 0 || nb == 0)*/
  dest[i] = '\0';
  return (dest);
}

static char	*add_to_line(char *line, int cure, char *buff, int *start)
{
  char		*new_elem;
  int		old_len;

  if (line != 0)
    old_len = my_strlen(line);
  else
    old_len = 0;
  new_elem = my_malloc((old_len + cure + 1) * sizeof(*new_elem));
  if (new_elem == NULL) /* Modification après soutenance */
    return (NULL); /* Modification après soutenance */
  if (line != 0)
    my_strncpy(new_elem, line, old_len);
  else
    my_strncpy(new_elem, "", old_len);
  my_strncpy(new_elem + old_len, buff + *start, cure);
  new_elem[old_len + cure] = 0;
  if (line)
    free(line);
  *start = *start + (cure + 1);
  return (new_elem);
}

char		*get_next_line(const int fd)
{
  static char	buff[MEM_SIZE];
  static int	in_buff = 0;
  static int	start;
  int		cure;
  char		*line;

  line = 0;
  cure = 0;
  while (42) /* A bas les boucles inf !!*/
    {
      if (start >= in_buff)
	{
	  start = 0;
	  if (!(in_buff = read(fd, buff, MEM_SIZE)))
	    return (line);
	  if (in_buff == -1)
	    return (NULL);
	  cure = 0;
	}
      if (buff[start + cure] == '\n')
	{
	  if ((line = add_to_line(line, cure, buff, &start)) == NULL) /* Modification après soutenance */
	    return (NULL); /* Modification après soutenance */
	  else
	    return (line);
	}
      if (start + cure == in_buff - 1)
	line = add_to_line(line, cure + 1, buff, &start);
      cure = cure + 1;
    }
}
